//.服务地址
window.ServerUrl = "http://taokebao.taokeyun.cn";
//.版本控制(此处请自由发挥)
var APIversion = "V1";
//.接口地址
var APIurl = window.ServerUrl + '/api';
//.封装通信接口
window.APIServer = {
	"SendSms"        : APIurl + "/user/sendsms",//获取注册登录短信验证码 1
	"SmsLogin"       : APIurl + "/user/smslogin",//短信验证码登录 1
	'WxLogin'        : APIurl + '/user/wxlogin',//微信快捷登录 1
	'UserInfo'       : APIurl + '/user/userinfo',//获取用户基本信息 1
	'Wallet'         : APIurl + '/user/wallet',//我的钱包
	'BindWechat'     : APIurl + '/user/bind_wechat',//绑定微信 1
	'MoneyLogs'      : APIurl + '/user/money_logs',//资金记录
	'DrawCfg'        : APIurl + '/user/draw_cfg',//提现配置
	'Draw'           : APIurl + '/user/draw',//提现提交
	'Order'          : APIurl + '/user/order',//我的订单 1
	'History'        : APIurl + '/user/history',//我的足迹 1
	'HistoryDel'     : APIurl + '/user/history_del',//我的足迹删除 1
	'FindOrder'      : APIurl + '/user/find_order',//找回订单
	'BindPid'        : APIurl + '/user/bind_pid',//绑定上级pid 1
	//'Alipay'         : APIurl + '/user/alipay',//支付宝支付
	'AlipayH5'       : APIurl + '/user/alipay_h5',//支付宝h5支付 1
	//'Wxpay'          : APIurl + '/user/wxpay',//微信宝支付
	'BindMobile'     : APIurl + '/user/bind_mobile',//绑定手机 1
	'BindAlipay'     : APIurl + '/user/bind_alipay',//绑定支付宝 1
	'BindTb'         : APIurl + '/user/bind_taobao',//绑定淘宝信息 1
	'OrderCount'     : APIurl + '/user/order_count',//收入报表 1
	'Hb'             : APIurl + '/user/hb',//海报 1
	'Team'           : APIurl + '/user/team',//我的团队 1
	'TeamList'       : APIurl + '/user/team_list',//我团队会员列表 1
	'PayInfo'        : APIurl + '/user/pay_info',//支付信息 1
	'Agent'          : APIurl + '/user/agent',//代理商中心
	'Zhichi'         : APIurl + '/user/zhichi',//智齿客服
	'Duiba'          : APIurl + '/user/duiba',//兑吧
	'Task'           : APIurl + '/user/task',//任务中心
	'JPushId'        : APIurl + '/user/regid',//极光推送设备标识ID

	'Search'         : APIurl + '/lists/search',//搜索 1
	'Section'        : APIurl + '/lists/section',//版块信息 1
	'SectionGoods'   : APIurl + '/lists/section_goods',//版块商品 1
	'JdList'         : APIurl + '/lists/jd_list',//京东 1
	'Faquan'         : APIurl + '/lists/faquan',//发圈 1
	'PddOpt'         : APIurl + '/lists/pdd_opt',//拼多多查询商品标签列表 1

	'ItemInfo'       : APIurl + '/goods/item_info',//宝贝详情 1
	'Buy'            : APIurl + '/goods/buy',//购买 1
	'Share'          : APIurl + '/goods/share',//分享 1


	'TaokeCfg'       : APIurl + '/index/get_taoke_cfg',//淘客配置信息
	'HotWords'       : APIurl + '/index/hot_words',//热搜词 1
	'Suggest'        : APIurl + '/index/suggest',//建议关词 1
	'IndexLayout'    : APIurl + '/index/index_layout',//首页相关 1
	'SqHelp'         : APIurl + '/index/sq_help',//搜券教程 1
	'LoignCfg'       : APIurl + '/index/login_cfg',//登录配置 1

	'Statics'        : APIurl + '/statics',//静态地址
	'Detail'         : APIurl + '/detail',//文章

}

//珍购多 秋扬诺布
//window.ServerUrlZGD = "http://v2.api.haodanku.com";
window.APIServerZGD = {
    LimitTime: 'http://v2.api.haodanku.com/fastbuy/apikey/zhengouduo/hour_type/{hour_typeVal}/min_id/{min_idVal}',
    VideoGuide: 'http://v2.api.haodanku.com/column/apikey/zhengouduo/type/{typeVal}/back/{backVal}/min_id/{min_idVal}/sort/{sortVal}/cid/{cidVal}',
    NineNine: 'http://v2.api.haodanku.com/get_keyword_items/apikey/zhengouduo/keyword/{keywordVal}/type/{typeVal}/back/{backVal}/min_id/{min_idVal}/sort/{sortVal}',
    SuperClass: 'http://v2.api.haodanku.com/super_classify/apikey/zhengouduo',
	GoodGoods: 'http://v2.api.haodanku.com/subject_hot/apikey/zhengouduo/min_id/{min_idVal}',
	getProphetSay: 'http://v2.api.haodanku.com/talent_info/apikey/zhengouduo',
	getProphetSayItem: 'http://v2.api.haodanku.com/talent_article/apikey/zhengouduo/id/{id}',
}
window.urlTransformZGD = function(path, data) {
    var reg = /\{(.+?)\}/g,
        pathList = path.match(reg),
        newPath = path;
    if (pathList) {
        for (var i = 0; i < pathList.length; i++) {
            var element = pathList[i];
            if (data[element.slice(1, element.length - 1)] || data[element.slice(1, element.length - 1)] == '') {
                newPath = newPath.replace(element, data[element.slice(1, element.length - 1)])
                delete data[element.slice(1, element.length - 1)]
            }
        }
    }
    return newPath
}

function formatDateTime(inputTime) {
    var date = new Date(inputTime);
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    var minute = date.getMinutes();
    var second = date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;
    second = second < 10 ? ('0' + second) : second;
    return y + '-' + m + '-' + d + ' ' + h + ':' + minute;
}
//珍购多 秋扬诺布


//手机号正则
window.regex_mobile = /^((13[0-9]{1})|(14[0-9]{1})|(15[0-9]{1})|(16[0-9]{1})|(17[0-9]{1})|(18[0-9]{1})|(19[0-9]{1}))+\d{8}$/;
//ajax 超时时间
window.ajaxTimeout = 30;
//图像缓存目录
var BASE_IMG_HEAD_TEMP_PATH = 1;


//判断，这里只能用同步
function is_login() {
	var token = _GetPrefs('token');
	if (token != null && token != '' && typeof token != "undefined") {
		return true;
	}
	return false;
}
//退出登录
function logout() {
	_RemovePrefs('uid');
	_RemovePrefs('token');
	_RemovePrefs('uinfo');
	//广播事件：退出登录
	_SendEvent('UserLogout');
	openWin('login');
}
//close win
function closeWin() {
	api.closeWin({});
}
//openwin
function openWin(html, param) {
	param = param || {};
	//延时渲染 IOS有效
	var delay = 0;
	if ("ios" == api.systemType) {
		delay = 200;
	}
	api.openWin({
		name: html,
		url: 'widget://html/' + html + '.html',
		allowEdit: true,
		pageParam: param,
		useWKWebView:true,
		delay:delay
	});
}
//
function openFrame(frame_name, param) {
	param = param || {};
	api.openFrame({
		name: frame_name,
		url: 'widget://html/' + frame_name + '.html',
		rect: {
			x: 0,
			y: 0,
			w: 'auto',
			h: 'auto'
		},
		pageParam: param,
		bgColor: 'rgba(0,0,0,0)',
		vScrollBarEnabled: false,
		hScrollBarEnabled: false
	});
}
//打开native page
function openPublic(obj) {
	if (typeof obj == 'string') {
		var options = JSON.parse(obj);
		var framename = options.framename;
	} else {
		var title = $api.attr(obj, 'data-title');
		var framename = $api.attr(obj, 'data-frame');
		var other = $api.attr(obj, 'data-other') || '';
		var options = {
			title: title,
			framename: framename,
			other: other
		};
	}
	//延时渲染 IOS有效
	var delay = 0;
	if ("ios" == api.systemType) {
		delay = 200;
	}
	//适用全部打开新窗口操作
	api.openWin({
		name: framename,
		url: 'widget://html/public_win.html',
		pageParam: options,
		bounces: false,
		vScrollBarEnabled: false,
		hScrollBarEnabled: false,
		reload: true,
		delay: delay,
		useWKWebView:true
	});
}

function openWeb(obj) {
	var url = $api.attr(obj, 'data-url') || obj.url || '';
	if (!url) {
		return false;
	}
	var title = $api.attr(obj, 'data-title') || obj.title || '';
	var options = {
		title: title,
		url: url,
	}
	api.openWin({
		name: 'web',
		url: 'widget://html/web_win.html',
		pageParam: options
	});
}
//=============================== 数据 存储  偏好 设置  ============================

//.设置存储
function _SetStorage(key, value) {
	$api.setStorage(key, value);
}

//.获取存储
function _GetStorage(key) {
	return $api.getStorage(key);
}

//.移除存储
function _RemoveStorage(key) {
	return $api.rmStorage(key);
}

//.清除全部缓存
function _ClearStorage() {
	$api.clearStorage();
	_toast('清除缓存成功！');
}

//.设置偏好设置
function _SetPrefs(key, value) {
	api.setPrefs({
		key: key,
		value: value
	});
}

//.获取偏好设置,自动判断同步或者异步
function _GetPrefs(key, _call) {
	if (typeof _call == "function") {
		api.getPrefs({
			key: key
		}, function (ret, err) {
			var v = ret.value;
			_call(v);
		});
	} else {
		var v = api.getPrefs({
			sync: true,
			key: key
		});
		return v;
	}

}

//.移除偏好设置
function _RemovePrefs(key, _call) {
	api.removePrefs({
		key: key
	}, function (ret, err) {
		var v = ret.value;
		if (typeof _call == "function") {
			_call();
		}
	});
}
//=============================== UI 界面  载入  刷新  加载  ============================

//.重载页面
function _RefreshPage() {
	window.location.reload();
}

//.弹出框
function _toast(msg) {
	api.toast({
		msg: msg
		//location: 'middle'
	});
}
//.loading
function _loading(title, text, modal) {
	text = text || '';
	modal = modal || false;
	api.showProgress({
		title: title,
		text: text,
		modal: modal
	});
}

function _loading_close() {
	api.hideProgress();
}
//loading2
function _loading2() {
	var activity = api.require('UILoading');
	activity.keyFrame({
		rect: {
			w: 80,
			h: 100
		},
		styles: {
			bg: 'rgba(0,0,0,0)',
			corner: 5,
			interval: 50,
			frame: {
				w: 80,
				h: 80
			}
		},
		content: [{
				frame: 'widget://image/loading/ic_page_loading_frame2.png'
			},
			{
				frame: 'widget://image/loading/ic_page_loading_frame3.png'
			},
			{
				frame: 'widget://image/loading/ic_page_loading_frame4.png'
			},
			{
				frame: 'widget://image/loading/ic_page_loading_frame5.png'
			},
			{
				frame: 'widget://image/loading/ic_page_loading_frame6.png'
			},
			{
				frame: 'widget://image/loading/ic_page_loading_frame7.png'
			},
			{
				frame: 'widget://image/loading/ic_page_loading_frame8.png'
			},
			{
				frame: 'widget://image/loading/ic_page_loading_frame9.png'
			},
			{
				frame: 'widget://image/loading/ic_page_loading_frame10.png'
			},
			{
				frame: 'widget://image/loading/ic_page_loading_frame11.png'
			},
			{
				frame: 'widget://image/loading/ic_page_loading_frame12.png'
			},
			{
				frame: 'widget://image/loading/ic_page_loading_frame13.png'
			},
			{
				frame: 'widget://image/loading/ic_page_loading_frame14.png'
			},
			{
				frame: 'widget://image/loading/ic_page_loading_frame15.png'
			},
			{
				frame: 'widget://image/loading/ic_page_loading_frame16.png'
			},
			{
				frame: 'widget://image/loading/ic_page_loading_frame17.png'
			},
			{
				frame: 'widget://image/loading/ic_page_loading_frame18.png'
			},
			{
				frame: 'widget://image/loading/ic_page_loading_frame19.png'
			},
			{
				frame: 'widget://image/loading/ic_page_loading_frame20.png'
			},
		],
		//mask:'rgba(0,0,0,0)'
	});
}

function _loading2_close() {
	var uiloading = api.require('UILoading');
	uiloading.closeKeyFrame();
}
//下拉刷新
function _Refresh(_call) {
	api.setCustomRefreshHeaderInfo({
		bgColor: '#f0f0f0',
		refreshHeaderHeight: 60,
		loadAnimInterval: 200,
		isScale: true,
		image: {
			pull: [
				'widget://image/refresh/ic_red_point1.png',
				'widget://image/refresh/ic_red_point2.png',
				'widget://image/refresh/ic_red_point3.png',
				'widget://image/refresh/ic_red_point4.png',
				'widget://image/refresh/ic_red_point5.png',
				'widget://image/refresh/ic_red_point6.png',
				'widget://image/refresh/ic_red_point7.png',
				'widget://image/refresh/ic_red_point8.png',
				'widget://image/refresh/ic_red_point9.png',
				'widget://image/refresh/ic_red_point10.png',
				'widget://image/refresh/ic_red_point11.png',
				'widget://image/refresh/ic_red_point12.png',
				'widget://image/refresh/ic_red_point13.png',
				'widget://image/refresh/ic_red_point14.png',
				'widget://image/refresh/ic_red_point15.png',
				'widget://image/refresh/ic_red_point16.png',
			],
			load: [
				'widget://image/refresh/ic_red_point7.png',
				'widget://image/refresh/ic_red_point8.png',
				'widget://image/refresh/ic_red_point9.png',
				'widget://image/refresh/ic_red_point10.png',
				'widget://image/refresh/ic_red_point11.png'
			]
		}

	}, function () {
		//下拉刷新被触发，自动进入加载状态，使用 api.refreshHeaderLoadDone() 手动结束加载中状态
		//下拉刷新被触发，使用 api.refreshHeaderLoadDone() 结束加载中状态
		setTimeout(function () {
			api.refreshHeaderLoadDone();
			if (typeof _call == "function") {
				_call();
			} else {
				_RefreshPage();
			}
		}, 600)

	});
}
//图片缓存
//<img class="img" src="占位图" _src="网络图">
function imageCache(dom) {
	var srcs = $api.domAll(dom);
	if (srcs.length > 0) {
		for (var i = 0; i < srcs.length; i++) {
			(function (obj) {
				if ($api.attr(obj, '_src') != '') {
					api.imageCache({
						url: $api.attr(obj, '_src')
					}, function (ret, err) {
						if (ret) {
							$api.attr(obj, 'src', ret.url);
						}
					});
				}
			})(srcs[i]);
		}
	}
}
//下载图片缓存
function imagedown(dom) {
	var srcs = $api.domAll(dom);
	if (srcs.length > 0) {
		for (var i = 0; i < srcs.length; i++) {
			(function (obj) {
				if ($api.attr(obj, '_src') != '') {
					api.download({
						url: $api.attr(obj, '_src'),
						report: false,
						cache: true,
						allowResume: true
					}, function (ret, err) {
						if (ret.state == 1) {
							//下载成功
							$api.attr(obj, 'src', ret.savePath);
						}
					});
				}
			})(srcs[i]);
		}
	}
}
//=============================== 广播  监听 跨窗口执行脚本  ============================

//.广播事件
function _SendEvent(eventName, extra) {
	var _extra = (typeof arguments[1] == "undefined" || arguments[1] == null) ? {} : arguments[1];
	api.sendEvent({
		name: eventName,
		extra: _extra
	});
}

//.监听事件
function _AddEventListener(eventName, _call, extra) {
	var _extra = (typeof arguments[2] == "undefined" || arguments[2] == null) ? {} : arguments[2];
	api.addEventListener({
		name: eventName,
		extra: _extra
	}, function (ret, err) {
		if (typeof _call == "function") {
			_call(ret);
		}
	});
}


// 异步请求
function _Ajax(url, method, data, dataType, _callback, _callbackerr, headers, cache, timeout, tag) {
	var _data = (typeof arguments[2] == "undefined" || arguments[2] == null) ? {} : arguments[2];
	var _dataType = (typeof arguments[3] == "undefined" || arguments[3] == null) ? "json" : arguments[3];
	var _headers = (typeof arguments[5] == "undefined" || arguments[5] == null) ? {} : arguments[5];
	var _cache = (typeof arguments[6] == "undefined" || arguments[6] == null) ? false : arguments[6];
	var _timeout = (typeof arguments[7] == "undefined" || arguments[7] == null) ? window.ajaxTimeout : arguments[7];
	var _tag = (typeof arguments[8] == "undefined" || arguments[8] == null) ? '' : arguments[8];

	//加个认证信息，这里要用异步
	var token = _GetPrefs('token');
	var uid = _GetPrefs('uid');
	if (token != '' && uid != '') {
		var auth_data = {
			values: {
				token: token,
				uid: uid
			}
		}
		mergeJSON(auth_data, _data);
	}
	var logData = {
		url: url,
		cache: _cache,
		//tag : _tag,
		method: method,
		headers: _headers,
		timeout: _timeout,
		dataType: _dataType,
		returnAll: false,
		data: _data
	}
	//console.log(JSON.stringify(logData))
	api.ajax({
		url: url,
		cache: _cache,
		//tag : _tag,
		method: method,
		headers: _headers,
		timeout: _timeout,
		dataType: _dataType,
		returnAll: false,
		data: _data
	}, function (ret, err) {
		if (ret) {
			if (ret.code == 501 || ret.code == 502) {
				_loading_close();
				_loading2_close();
				logout();
				return false;
			}
			//.回调函数
			if (typeof _callback == "function") {
				_callback(ret);
			}
		} else {
			//.错误处理
			if (typeof _callbackerr == "function") {
				_callbackerr(err);
				_toast("服务器正在加载中...");
			} else {
				_toast("服务器正在加载中...");
			}
		}
	});
}
// 遇到相同元素级属性，以后者（main）为准
// 不返还新Object，而是main改变
function mergeJSON(minor, main) {
	for (var key in minor) {

		if (main[key] === undefined) { // 不冲突的，直接赋值
			main[key] = minor[key];
			continue;
		}

		// 冲突了，如果是Object，看看有么有不冲突的属性
		// 不是Object 则以main为主，忽略即可。故不需要else
		if (isJSON(minor[key])) {
			// arguments.callee 递归调用，并且与函数名解耦
			arguments.callee(minor[key], main[key]);
		}
	}
}

// 附上工具
function isJSON(target) {
	return typeof target == "object" && target.constructor == Object;
}




//打开产品
function open_goods(data) {
	//需要登录
	if (!is_login()) {
		openWin('login');
		api.closeWin({
			name: 'search_win',
			animation: {
				type: 'none'
			}
		});
		return false;
	}
	api.openWin({
		name: data.win_name || 'goods_detail_win',
		url: 'widget://html/goods_detail_win.html',
		pageParam: {
			data: data
		}
	});
}
//复制文案
function copy(text) {
	var clipBoard = api.require('clipBoard');
	clipBoard.set({
		value: text
	}, function (ret, err) {
		if (ret.status) {
			_toast('已复制到剪切板');
		} else {
			_toast('复制失败');
		}
	});
}
//智齿客服
function zhichi(){
	_loading('启动中')
	_Ajax(window.APIServer.Zhichi,'post',{values:{}},'json',function(ret){
		_loading_close();
		if (ret.code==1) {
			var zhichi = api.require('zhiChiSobot');
			zhichi.startZhiChiSobot(ret.data.param,function(ret,err){
			    //alert("ret.type="+ret.type+"\nvalue="+ret.value+"\nret.desc="+ret.desc);
			});
		}else{
			_toast(ret.msg);
		}
	})
}
//腾讯X5引擎
function txweb_open(url){
	var browser = api.require('webBrowser');
	browser.open({
	    url: url,
	    titleBar:{
	    	visible:true,      //标题栏是否隐藏，只支持Android，布尔类型，默认值false
	        bg:'#fff',             //标题栏背景颜色，支持 rgb，rgba，#fff等，默认值#393A3F
	        textColor:'#333',    //标题栏文字颜色，支持 rgb，rgba，#fff等，默认值#FFF
	    }
	});
}
//积分商城
function duiba(type){
  _loading2();
  _Ajax(window.APIServer.Duiba,'post',{values:{}},'json',function(ret){
    _loading2_close();
      if (ret.code==1) {
        if (type=='sign') {
          openWeb({url:ret.data.sign_url,title:'每日签到'});
        }else{
          openWeb({url:ret.data.autologin_url,title:'积分商城'});
        }

      }else{
          _toast(ret.msg)
      }
  })
}

//随机字符串
function randomString(len) {
　　len = len || 32;
　　var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz123456789';
　　var maxPos = $chars.length;
　　var pwd = '';
　　for (i = 0; i < len; i++) {
　　　　pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
　　}
　　return pwd;
}
